package cn.wujiangbo.service.system;

import cn.wujiangbo.constants.ErrorCode;
import cn.wujiangbo.domain.system.SysUser;
import cn.wujiangbo.exception.MyException;
import cn.wujiangbo.mapper.system.SysUserMapper;
import cn.wujiangbo.query.system.SysUserQuery;
import cn.wujiangbo.result.JSONResult;
import cn.wujiangbo.util.MyTools;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 波波老师(weixin:javabobo0513)
 */
@Service
@Slf4j
@Transactional
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser>{

    @Resource
    private RedisTemplate redisTemplate;

    //查询分页列表数据
    public IPage<SysUser> selectMyPage(SysUserQuery query) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (MyTools.hasLength(query.getKeyword())) {
            wrapper.and(i -> i.like("user_name", query.getKeyword()));
        }
        //排序
        wrapper.orderByDesc("create_time").orderByDesc("id");
        IPage<SysUser> page = new Page<>(query.getCurrent(), query.getSize());
        return super.page(page, wrapper);
    }

    //获取用户个人信息
    public JSONResult getUSerInfo(String token) {
        if(StringUtils.hasLength(token)){
            Object userInfo = redisTemplate.opsForValue().get(token);
            if(userInfo == null){
                throw new MyException(ErrorCode.ERROR_CODE_1002.getMessage());
            }
            SysUser sysUser = JSONObject.parseObject(userInfo.toString(), SysUser.class);
            Map<String, String> map = new HashMap<>();
            map.put("name", sysUser.getUsername());
            map.put("avatar", sysUser.getAvatar());
            return JSONResult.success(map);
        }
        else{
            throw new MyException(ErrorCode.ERROR_CODE_1008.getMessage());
        }
    }
}
